import time  
from tinydb import TinyDB, Query  

class IdManager:  
    def __init__(self):  
        self.next_id = 1  # 用于分配新的ID  
        self.object_dict = {}  # 用于存储物体的字典，key为ID，value为bbox、类别和上一次出现的时间戳  
        self.iou_threshold = 0.5  # IOU阈值，用于确定两个bbox是否匹配  
        self.timestamp = time.time()  # 使用当前时间的时间戳
        print(self.timestamp)
        # 初始化TinyDB数据库  
        self.db = TinyDB('matches.json')  
  
    def assign_id(self, detection):  
        """为检测到的物体分配一个新的ID"""  
        detection['id'] = self.next_id  
        self.next_id += 1  
        self.object_dict[detection['id']] = {'bbox': detection['bbox'], 'class': detection['class'], 'last_seen': 0}  
  
    def update_last_seen(self, detection_id,frame):  
        """更新物体最后出现的时间戳（这里简化为帧计数）"""  
        self.object_dict[detection_id]['last_seen'] = frame  

    def match_objects(self, detections,frame):  
        """在当前帧中匹配已知物体，并为新物体分配ID"""  
        unmatched_detections = detections.copy()  # 未匹配的检测列表  
        new_ids = []  # 存储新分配的ID  
  
        # 第一步：尝试匹配已知物体  
        for detection in detections:  
            for obj_id, obj in self.object_dict.items():  
                print("obj_id")
                print(obj['bbox'])
                print(detection['bbox'])
                print(obj['class'])
                print(detection['class'])
                if self.is_match(obj['bbox'], detection['bbox'], obj['class'], detection['class']):  
                    detection['id'] = obj_id  
                    self.update_last_seen(obj_id,frame)  
                    unmatched_detections.remove(detection)  
                    match_dict = {  
                        'timestamp': self.timestamp,  
                        'id': obj_id,  
                        'class':obj['class'],  
                        'bbox': detection['bbox'],  
                        'framestamp': frame  
                    }  
                    # 插入到数据库  
                    self.db.insert(match_dict) 
                    break  
  
        # 第二步：为未匹配的物体分配新ID  
        for detection in unmatched_detections:  
            self.assign_id(detection)  
            new_ids.append(detection['id'])  
            match_dict = {  
                'timestamp': self.timestamp,  
                'id': detection['id'],  
                'class':detection['class'],  
                'bbox': detection['bbox'],  
                'framestamp': frame  
            }  
            # 插入到数据库  
            self.db.insert(match_dict) 
  
        # 第三步：移除长时间未出现的物体（可选）  
        # 这里可以添加一个逻辑来移除在一定帧数内未出现的物体  
        
        return detections, new_ids 

        # 第二步：为未匹配的物体分配新ID  
        for detection in unmatched_detections:  
            self.assign_id(detection)  
            new_ids.append(detection['id'])  
            match_dict = {  
                'timestamp': self.timestamp,  
                'id': detection['id'],  
                'class':detection['class'],  
                'bbox': detection['bbox'],  
                'framestamp': frame  
            }  
            # 插入到数据库  
            self.db.insert(match_dict) 
  
        # 第三步：移除长时间未出现的物体（可选）  
        # 这里可以添加一个逻辑来移除在一定帧数内未出现的物体  
        
        return detections, new_ids  
  
    #@staticmethod  
    def is_match(self,bbox1, bbox2, class1, class2):  
        """判断两个bbox是否匹配，并且它们的类别是否相同"""  
        # 假设bbox格式为 [left, top, right, bottom]
        iou = 0  
        if class1 == class2:
            x1 = bbox1[0]  
            y1 = bbox1[1]  
            x2 = bbox1[2]  
            y2 = bbox1[3]  
            x3 = bbox2[0]  
            y3 = bbox2[1]  
            x4 = bbox2[2]  
            y4 = bbox2[3]  
            # 计算交集区域的坐标  
            xx1 = max(x1, x3)  
            yy1 = max(y1, y3)  
            xx2 = min(x2, x4)  
            yy2 = min(y2, y4)  
            # 计算交集区域的宽和高  
            inter_w = max(0, xx2 - xx1)  
            inter_h = max(0, yy2 - yy1)  
		    # 计算交集面积  
            intersection = inter_w * inter_h  
            # 计算两个bbox的面积  
            box1_area = (x2 - x1) * (y2 - y1)  
            box2_area = (x4 - x3) * (y4 - y3)  
            # 计算IOU  
            iou = intersection / float(box1_area + box2_area - intersection + 1e-6)  
            # 判断IOU是否超过阈值，并且类别相同  
        print(iou)
        return iou > 0.5 and class1 == class2

